package urnoted;

import javax.sound.midi.*;

public class NoteSynthesizer {
    static final int DURATION = 1000;  // milliseconds to be played
    static final int VOLUME = 60;
    private Synthesizer synthesizer;
    private Receiver receiver;

    public NoteSynthesizer() {
        try {
            synthesizer = MidiSystem.getSynthesizer();
            synthesizer.open();
            receiver = synthesizer.getReceiver();
        } catch (MidiUnavailableException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void playNote(Note note) {
        int pitch = note.getPitch();  // the note to be played
        MidiMessage noteOn = getMessage(ShortMessage.NOTE_ON, pitch);
        receiver.send(noteOn, 5);
        /*try {
            Thread.sleep(DURATION);  // hold the note this long
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        MidiMessage noteOff = getMessage(ShortMessage.NOTE_OFF, pitch);
        receiver.send(noteOff, 0);
    }
    
    public void playNote(Note note, long delay) {
        try {
            Thread.sleep(delay);  // hold the note this long
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int pitch = note.getPitch();  // the note to be played
        MidiMessage noteOn = getMessage(ShortMessage.NOTE_ON, pitch);
        receiver.send(noteOn, 5);
        MidiMessage noteOff = getMessage(ShortMessage.NOTE_OFF, pitch);
        receiver.send(noteOff, 0);
    }

    private MidiMessage getMessage(int command, int note) {
        try {
            ShortMessage msg = new ShortMessage();
            msg.setMessage(command, 0, note, VOLUME);
            return (MidiMessage) msg;
        } catch (InvalidMidiDataException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return null;
    }
}